<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
				<el-button class="uni-button" type="success"  size="mini" @click="navigateTo('./add')">新增</el-button>
				<el-button class="uni-button" type="default" size="mini" @click="navigateTo('./statistics')">统计信息</el-button>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db
				ref="udb"
				:collection="collectionName"
				:options="options"
				:where="where"
				page-data="replace"
				:orderby="orderby"
				:getcount="true"
				:page-size="options.pageSize"
				:field="fields"
				:page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error }"
			>
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">头像</uni-th>
						<uni-th align="center">昵称</uni-th>
						<uni-th align="center">手机号</uni-th>
						<uni-th align="center">注册时间</uni-th>
						<uni-th align="center">最后登录时间</uni-th>
						<uni-th align="center">护工申请状态</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">
							<el-image :src="item.avatar" class="user-avatar" :preview-src-list="[item.avatar]"></el-image>
						</uni-td>
						<!-- <uni-td align="center">{{ item.username }}</uni-td> -->
						<uni-td align="center">{{ item.nickname }}</uni-td>
						<uni-td align="center">{{ item.mobile }}</uni-td>
						<uni-td align="center"><uni-dateformat :date="item.register_date" :threshold="[0, 0]" /></uni-td>
						<uni-td align="center"><uni-dateformat :date="item.last_login_date" :threshold="[0, 0]" /></uni-td>
						<uni-td align="center">{{ item.status | activeFilter }}</uni-td>
						<uni-td align="center" v-if="item.realname_auth">{{ item.realname_auth.auth_status | statusFilter }}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<el-button size="mini"  class="uni-button" type="warning" v-if="item.status==2"  @click="checkDialog(item)">审核</el-button>
								<button @click="navigateTo('./edit?id=' + item._id)" class="uni-button" size="mini" type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<view>
			<el-dialog title="审核" :visible.sync="dialogFormVisible">
				<el-form :model="checkForm" :rules="rules" ref="checkForm">
					<el-form-item label="审核状态" :label-width="formLabelWidth" prop="status">
						<el-radio-group v-model="checkForm.status">
							<el-radio :label="0">通过</el-radio>
							<el-radio :label="3">审核拒绝</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="审核原因" :label-width="formLabelWidth" prop="status_msg">
						<el-input v-model="checkForm.status_msg" :rows="5" placeholder="审核原因" style="width:400px"
							type="textarea" autocomplete="off"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="checkSubmit('checkForm')">确 定</el-button>
				</div>
			</el-dialog>
		</view>
	</view>
</template>

<script>
const db = uniCloud.database();
// 表查询配置
const dbCollectionName = 'uni-id-users';
const dbOrderBy = 'username desc'; // 排序字段
const dbSearchFields = ['username', 'mobile']; // 支持模糊搜索的字段列表
// 分页配置
const pageSize = 15;
const pageCurrent = 1;
const fields ='_id,username,nickname,email,status,realname_auth,my_invite_code,mobile,type,tel,avatar,name,sex,age,level,exp_year,tags,identity_no,identity_img,zodiac,constellation,native_place,nation,education,examination,background_checks,certificates,introduce,comment,photos,care_item,training_records,arrangement';

const typeMap = { 0: '个人用户', 1: '企业用户' };
const statusMap = { 0: '未认证', 1: '等待认证',2:'认证通过',3:'认证失败' };
const activeMap={ 0:'正常',1:'禁用',2:'审核中',3:'审核拒绝'};
export default {
	data() {
		return {
			formLabelWidth: '120px',
			rules: {
				status: [ { required: true, message: '请选择审核状态', trigger: 'change' }],
				status_msg: [{
					required: true,
					message: '请填写审核原因',
					trigger: 'blur'
				}]
			},
			dialogFormVisible: false,
			checkForm: {
				check_user_id: '',
				status: null,
				status_msg: null
			},
			fields: fields,
			query: '',
			where: 'role=="user"',
			orderby: dbOrderBy,
			collectionName: dbCollectionName,
			options: {
				pageSize,
				pageCurrent
			}
		};
	},
	filters: {
		typeFilter(type) {
			return typeMap[type];
		},
		statusFilter(type) {
			return statusMap[type];
		},
		activeFilter(active){
			return activeMap[active];
		}
	},
	methods: {
		getWhere() {
			const query = this.query.trim();
			if (!query) {
				return '';
			}
			const queryRe = new RegExp(query, 'i');
			return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
		},
		search() {
			const newWhere = this.getWhere();
			const isSameWhere = newWhere === this.where;
			this.where = newWhere;
			if (isSameWhere) {
				// 相同条件时，手动强制刷新
				this.loadData();
			}
		},
		loadData(clear = true) {
			this.$refs.udb.loadData({
				clear
			});
		},
		onPageChanged(e) {
			this.$refs.udb.loadData({
				current: e.current
			});
		},
		navigateTo(url) {
			uni.navigateTo({
				url,
				events: {
					refreshData: () => {
						this.loadData();
					}
				}
			});
		},
		// 多选处理
		selectedItems() {
			var dataList = this.$refs.udb.dataList;
			return this.selectedIndexs.map(i => dataList[i]._id);
		},
		//批量删除
		delTable() {
			this.$refs.udb.remove(this.selectedItems());
		},
		// 多选
		selectionChange(e) {
			this.selectedIndexs = e.detail.index;
		},
		confirmDelete(id) {
			this.$refs.udb.remove(id);
		},
		checkSubmit(formName) {
			const that = this;
			this.$refs[formName].validate(valid => {
				if (valid) {
					db.collection(dbCollectionName)
						.doc(this.formDataId)
						.update(this.checkForm)
						.then(res => {
							that.$message({
								showClose: true,
								message: '恭喜你，审核成功',
								type: 'success'
							});
							that.dialogFormVisible = false;
							that.getOpenerEventChannel().emit('refreshData');
							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							that.$message({
								showClose: true,
								message: '错了哦，请重试',
								type: 'error'
							});
						});
				} else {
					that.$message({
						showClose: true,
						message: '错了哦，请重试',
						type: 'error'
					});
					return false;
				}
			});
		},
		checkDialog(row) {
			this.formDataId = row._id;
			this.checkForm = {
				check_user_id: '',
				status: 2,
				status_msg: null
			};
			this.dialogFormVisible = true;
		},
	}
};
</script>
<style lang="scss">
.suoluetu {
	width: 100rpx;
	height: 100rpx;
}
.user-avatar{width: 40px; height: 40px;}
</style>
